import { addTag, updateTag } from "@/api/content/tag";
import { Tag } from "@/types/content/tag";
import { Form, Input, message, Modal, Spin } from "antd";
import { useForm } from "antd/es/form/Form";
import { useEffect, useState } from "react";
interface Props {
  isModalOpen: boolean;
  optionType: "add" | "edit";
  oldInfo?: Tag.Row;
  close?: () => void;
  change?: () => void;
}
export default function OptionForm(props: Props) {
  const [loading, setLoading] = useState(false);
  const [form] = useForm();
  const [messageApi] = message.useMessage();
  /**
   * 添加接口
   * @param data
   */
  const addTagInf = async (data: Tag.Form) => {
    setLoading(true);
    const res = await addTag(data);
    setLoading(false);
    if (res.code === 200) {
      messageApi.success("新增成功");
      props.close && props.close();
      props.change && props.change();
    }
  };
  /**
   * 修改接口
   * @param data
   */
  const updateTagInf = async (data: Tag.Form) => {
    setLoading(true);
    const res = await updateTag(data);
    setLoading(false);
    if (res.code === 200) {
      messageApi.success("修改成功");
      props.close && props.close();
      props.change && props.change();
    }
  };
  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const { name, remark } = values;
      const params = {
        name,
        remark,
      };
      if (props.optionType === "add") {
        addTagInf(params);
      } else if (props.optionType === "edit") {
        updateTagInf({
          ...(props.oldInfo || {}),
          ...params,
          id: props.oldInfo?.id,
        });
      }
    } catch (errorInfo) {
      console.log("Failed:", errorInfo);
    }
  };
  useEffect(() => {
    if (props.optionType === "edit") {
      form.setFieldsValue({
        name: props.oldInfo?.name || "",
        remark: props.oldInfo?.remark || "",
      });
    }
  }, [form, props.oldInfo?.name, props.oldInfo?.remark, props.optionType]);
  return (
    <Modal
      title={props.optionType === "add" ? "新增标签" : "修改标签"}
      open={props.isModalOpen}
      onOk={handleOk}
      onCancel={() => props.close && props.close()}
    >
      <Spin spinning={loading}>
        <Form
          form={form}
          name="tagOptionForm"
          size="middle"
          autoComplete="off"
          layout="vertical"
        >
          <Form.Item<Tag.Form>
            name="name"
            label="标签名称"
            rules={[
              { required: true, message: "请输入!" },
              { max: 20, message: "标签名称最长20个字" },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item<Tag.Form>
            name="remark"
            label="描述"
            rules={[{ max: 50, message: "备注最长50个字" }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
}
